import React, { useCallback, useMemo, useEffect, useRef } from "react";
import { Modal, Form, Input, Radio, message } from "antd";
import { UserOutlined, KeyOutlined } from "@ant-design/icons";
import {
  postAdminItemApi,
  getAdminItemApi,
  updateAdminItemApi,
} from "@/api/user";
import CustomTree from "./Tree";
export default function AdminModal(props) {
  const { open, toggleOpen, adminname, refresh } = props;
  console.log("传入的admin", adminname);
  const [form] = Form.useForm();
  // 设置表单初始值
  const initialState = useRef({
    adminname: "",
    password: "",
    confirm: "",
    role: 1,
    checkedKeys: [],
  });
  const title = useMemo(
    () => (adminname ? "编辑管理员" : "新增管理员"),
    [adminname]
  );
  const toggleAndReset = useCallback(() => {
    form.setFieldsValue(initialState.current);
    toggleOpen();
  }, [toggleOpen, form]);
  // 保存区分新增编辑
  const handleOk = useCallback(() => {
    form
      .validateFields()
      .then(async (values) => {
        try {
          if (!adminname) {
            await postAdminItemApi(values);
          } else {
            await updateAdminItemApi(values);
          }
          toggleAndReset();
          refresh();
        } catch (error) {
          console.log("接口错误", error);
        }
      })
      .catch((err) => {
        message.error(err);
      });
  }, [toggleOpen, adminname]);
  const handleCancel = useCallback(() => {
    toggleAndReset();
  }, [toggleOpen]);
  // 设置默认值
  useEffect(() => {
    if (open) {
      console.log("进来编辑了", open);
      // 新建设置默认值 编辑设置相关接口值
      if (adminname) {
        getAdminItemApi(adminname).then((res) => {
          console.log("获取值", res);
          if (res[0]) {
            form.setFieldsValue(res[0]);
          } else {
            message.error("未查询到相关行信息，请重试");
          }
        });
      } else {
        form.setFieldsValue(initialState.current);
      }
    }
  }, [form, adminname, open]);

  return (
    <Modal
      title={title}
      open={open}
      onOk={handleOk}
      onCancel={handleCancel}
      width={"40%"}
    >
      <Form form={form} labelCol={{ span: 5 }} wrapperCol={{ span: 16 }}>
        <Form.Item
          label="用户名"
          name="adminname"
          rules={[
            { required: true, message: "用户名必填!" },
            { max: 12, min: 2, message: "用户名需要在2-12位" },
          ]}
        >
          <Input
            disabled={adminname}
            autoComplete="off"
            prefix={<UserOutlined className="form-prefix-icon" />}
            placeholder="请输入用户名！"
          />
        </Form.Item>
        {!adminname && (
          <>
            <Form.Item
              label="密码"
              name="password"
              validateTrigger="onBlur"
              rules={[
                { required: true, message: "密码必填!" },
                { max: 12, min: 6, message: "密码需要在6-12位" },
              ]}
            >
              <Input.Password
                autoComplete="off"
                prefix={<KeyOutlined />}
                placeholder="请输入密码!"
              />
            </Form.Item>
            <Form.Item
              name="confirm"
              label="确认密码"
              dependencies={["password"]}
              hasFeedback
              rules={[
                {
                  required: true,
                  message: "Please confirm your password!",
                },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue("password") === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error("两次输入不一致"));
                  },
                }),
              ]}
            >
              <Input.Password />
            </Form.Item>
          </>
        )}
        <Form.Item
          label="角色"
          name="role"
          rules={[{ required: true, message: "角色必填!" }]}
        >
          <Radio.Group>
            <Radio value={1}>管理员</Radio>
            <Radio value={2}>超级管理员</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item
          label="权限"
          name="checkedKeys"
          rules={[{ required: true, message: "角色必填!" }]}
        >
          <CustomTree />
        </Form.Item>
      </Form>
    </Modal>
  );
}
